package com.jy.modules.cims.common.sysUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.poi.ss.formula.functions.T;

/**
 * @description Collections工具集。 在JDK的Collections和Guava的Collections2后,
 *              命名为CollectionsUtils。 函数主要由两部分组成，一是自反射提取元素的功能，二是源自Apache Commons
 *              Collection, 争取不用在项目里引入它。
 * @version v1.0
 * @author ShengZhoutao
 * @Date 2012-9-27
 */
public final class CollectionsUtils {
	public static final int LIST_SIZE = 1000;
	/**
	 * 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
	 * 
	 * @param collection
	 *            来源集合.
	 * @param keyPropertyName
	 *            要提取为Map中的Key值的属性名.
	 * @param valuePropertyName
	 *            要提取为Map中的Value值的属性名.
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Map extractToMap(final Collection collection, final String keyPropertyName, final String valuePropertyName)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		Map map = new HashMap(collection.size());

		for (Object obj : collection) {
			map.put(PropertyUtils.getProperty(obj, keyPropertyName), PropertyUtils.getProperty(obj, valuePropertyName));
		}

		return map;
	}

	/**
	 * 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
	 * 
	 * @param collection
	 *            来源集合.
	 * @param propertyName
	 *            要提取的属性名.
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static List extractToList(final Collection collection, final String propertyName) throws IllegalAccessException,
			InvocationTargetException, NoSuchMethodException {
		List list = new ArrayList(collection.size());

		for (Object obj : collection) {
			list.add(PropertyUtils.getProperty(obj, propertyName));
		}

		return list;
	}

	/**
	 * 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
	 * 
	 * @param collection
	 *            来源集合.
	 * @param propertyName
	 *            要提取的属性名.
	 * @param separator
	 *            分隔符.
	 * @throws NoSuchMethodException
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 */
	@SuppressWarnings("rawtypes")
	public static String extractToString(final Collection collection, final String propertyName, final String separator)
			throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		List list = extractToList(collection, propertyName);
		return SimpleStringUtils.join(list, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
	 */
	@SuppressWarnings("rawtypes")
	public static String convertToString(final Collection collection, final String separator) {
		return SimpleStringUtils.join(collection, separator);
	}

	/**
	 * 转换Collection所有元素(通过toString())为String,
	 * 每个元素的前面加入prefix，后面加入postfix，如<div>mymessage</div>。
	 */
	@SuppressWarnings("rawtypes")
	public static String convertToString(final Collection collection, final String prefix, final String postfix) {
		StringBuilder builder = new StringBuilder();
		for (Object o : collection) {
			builder.append(prefix).append(o).append(postfix);
		}
		return builder.toString();
	}

	/**
	 * 判断是否为空.
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isEmpty(Collection collection) {
		return (collection == null || collection.isEmpty());
	}

	/**
	 * 判断是否为空.
	 */
	@SuppressWarnings("rawtypes")
	public static boolean isNotEmpty(Collection collection) {
		return (collection != null && !(collection.isEmpty()));
	}

	/**
	 * 取得Collection的第一个元素，如果collection为空返回null.
	 */
	public static <T> T getFirst(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}

		return collection.iterator().next();
	}

	/**
	 * 获取Collection的最后一个元素 ，如果collection为空返回null.
	 */
	public static <T> T getLast(Collection<T> collection) {
		if (isEmpty(collection)) {
			return null;
		}

		// 当类型为List时，直接取得最后一个元素 。
		if (collection instanceof List) {
			List<T> list = (List<T>) collection;
			return list.get(list.size() - 1);
		}

		// 其他类型通过iterator滚动到最后一个元素.
		Iterator<T> iterator = collection.iterator();
		while (true) {
			T current = iterator.next();
			if (!iterator.hasNext()) {
				return current;
			}
		}
	}

	/**
	 * 返回a+b的新List.
	 */
	public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
		List<T> result = new ArrayList<T>(a);
		result.addAll(b);
		return result;
	}

	/**
	 * 返回a-b的新List.
	 */
	public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
		List<T> list = new ArrayList<T>(a);
		for (T element : b) {
			list.remove(element);
		}

		return list;
	}

	/**
	 * 返回a与b的交集的新List.
	 */
	public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
		List<T> list = new ArrayList<T>();

		for (T element : a) {
			if (b.contains(element)) {
				list.add(element);
			}
		}
		return list;
	}

	/**
	 * 返回list的包装类的clazz新List.
	 */
	public static <T, S> List<T> copyProperties(List<S> list, Class<T> clazz) {
		List<T> result = new ArrayList<T>();

		if (list == null) {
			return result;
		}

		for (S s : list) {
			try {
				T o = clazz.newInstance();
				PropertyUtils.copyProperties(o, s);
				result.add(o);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 按perSize分割list
	 * @param allList
	 * @param perSize
	 * @return
	 */
	public static <T> List<List<T>> splitList(List<T> allList, int perSize) {
		List<List<T>> rsList = new ArrayList<List<T>>();
		if (CollectionsUtils.isEmpty(allList)
				|| allList.size() <= perSize) {
			rsList.add(allList);
		} else {
			int count = (allList.size() + perSize - 1)  / perSize;
			for (int i = 0; i < count; i++) {
				int startIdx = i * perSize;
				int endIdx = startIdx + perSize;
				if (endIdx > allList.size()) {
					endIdx = allList.size();
				}
				rsList.add(allList.subList(startIdx, endIdx));
			}
		}
		
		return rsList;
	}

}
